var modifyOrAddFlag;
// 定位显示
var arrayLi = [];
var arrayLiInd = 0;
$(document)
		.ready(
				function() {
					/* 系统树 */
					$('#system_selection').window({
						width : 310,
						height : 355,
						modal : true,
						minimizable : false,
						maximizable : false,
						collapsible : false,
						onClose : function() {
							$("#tt").html("");
						}
					});
					$('#system_selection').window('close'); // 关闭窗口
					$('#win').window('close');

					// 接口状态下拉框
					$('#comboxIsEnable').combobox(
							{
								url : BASE_URL_DATA_DICTIONARY_VALUE_SEARCH
										+ '/findByTypeCode?typeCode='
										+ DDTC_TOKEN_STATUS + '&v='
										+ Math.random(),
								valueField : 'valueCode',
								textField : 'valueName',
								editable : false,
								method : 'get',
								loadFilter : function(data) {
									var allCheck = {
										'valueCode' : '',
										'valueName' : '全部'
									};
									data.unshift(allCheck);
									return data;
								}
							});

					$('#comboxField')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '请选择'
											};
											if (data.content) {
												data.content.unshift(allCheck);
											} else {
												return data;
											}
											return data.content;
										},
										onSelect : function(record) {
											comboxSystem
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {

																	var allCheck = {
																		'id' : '',
																		'name' : '请选择'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onSelect : function(
																		record) {
																	/*comboxInterface
																			.combobox({
																				disabled : false,
																				method : 'get',
																				queryParams : {
																					fieldSystemId : record.id
																				},
																				url : BASE_URL_SYSTEM_INTERFACE_SEARCH
																						+ '/findByOwnerFieldSystem_Id'
																						+ '?v='
																						+ Math
																								.random(),
																				valueField : 'id',
																				textField : 'jobName',
																				data : '',
																				loadFilter : function(
																						data) {
																					if (data[0].id == "") {
																						return data;
																					}
																					var allCheck = {
																						'id' : '',
																						'jobName' : '请选择'
																					};
																					data
																							.unshift(allCheck);
																					return data;

																				},
																				onLoadSuccess : function() {
																					$(
																							'#comboxInterface')
																							.combobox(
																									'setValue',
																									'');
																				}
																			});*/
																},
																onLoadSuccess : function() {
																	$(
																			'#comboxInterface')
																			.combobox(
																					'setValue',
																					'');

																},
															// onChange :
															// function(
															// newValue,
															// oldValue) {
															// $(
															// '#datagrid4if')
															// .datagrid(
															// 'reload');
															// }
															}).load();
											/*comboxInterface.combobox({
												disabled : true,
												valueField : 'id',
												textField : 'jobName',
												editable : false,
												url : '',
												data : [],
												loadFilter : function(data) {
													var allCheck = {
														id : '',
														jobName : '请选择',
														'selected' : 'true'
													};
													data.unshift(allCheck);
													return data;
												}
											});*/
										},

									});

					var comboxSystem = $('#comboxSystem').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'name',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								name : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}

					});
					$('#comboxCallField')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '请选择'
											};
											if (data.content) {
												data.content.unshift(allCheck);
											} else {
												return data;
											}
											return data.content;
										},
										onSelect : function(record) {
											comboxCallSystem
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {

																	var allCheck = {
																		'id' : '',
																		'name' : '请选择'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onSelect : function(
																		record) {
																	comboxInterface4Call
																			.combobox({
																				disabled : false,
																				method : 'get',
																				queryParams : {
																					fieldSystemId : record.id
																				},
																				url : BASE_URL_SYSTEM_INTERFACE_SEARCH
																						+ '/findByOwnerFieldSystem_Id'
																						+ '?v='
																						+ Math
																								.random(),
																				valueField : 'id',
																				textField : 'jobName',
																				data : '',
																				loadFilter : function(
																						data) {
																					if (data[0].id == "") {
																						return data;
																					}
																					var allCheck = {
																						'id' : '',
																						'jobName' : '请选择'
																					};
																					data
																							.unshift(allCheck);
																					return data;

																				},
																				onLoadSuccess : function() {
																					$(
																							'#comboxInterface')
																							.combobox(
																									'setValue',
																									'');
																				}
																			});
																},
																onLoadSuccess : function() {
																	$(
																			'#comboxInterface')
																			.combobox(
																					'setValue',
																					'');

																}
															}).load();
											comboxInterface4Call.combobox({
												disabled : true,
												valueField : 'id',
												textField : 'jobName',
												editable : false,
												url : '',
												data : [],
												loadFilter : function(data) {
													var allCheck = {
														id : '',
														jobName : '请选择',
														'selected' : 'true'
													};
													data.unshift(allCheck);
													return data;
												}
											});
										}

									});

					var comboxCallSystem = $('#comboxCallSystem').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'name',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								name : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}

					});

					$("#datagrid")
							.datagrid(
									{
										url : BASE_URL_API
												+ '/channelSystemManagement/findInterfaceTokenInfos?v='
												+ Math.random(),
										method : 'get',
										autoRowHeight : true,
										singleSelect : true,
										striped : true,
										nowrap : false,
										pageSize : 20,
										pageList : [ 10, 20, 50, 100 ],
										columns : [ [
												{
													field : 'fieldName',
													title : '领域',
													width : 20,													
													align : 'center'
												},
												{
													field : 'systemName',
													title : '系统',
													width : 20,
													align : 'center'
												},
												{
													field : 'interfaceName',
													title : '接口名称',
													width : 60,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return '<a href="javascript:void(0)" style="padding-bottom: 0px;margin-bottom: 50px" onclick="showDetial('
																+ rowIndex
																+ ')">'
																+ value
																+ '</a>';
													}
												},
												{
													field : 'visibleListName',
													title : '允许拥有以下系统用户可见',
													width : 80,
													align : 'left'
												},
												{
													field : 'bu',
													title : '操作',
													width : 10,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return '<a href="javascript:void(0)" class="default_btn fl" onclick="selVisibleList('
																+ rowIndex
																+ ')">指定</a>';
													}
												} ] ],
										pagination : true,
										onSelect : function(rowIndex, rowData) {
										},
										onUnselect : function() {
										},
										loadFilter : function(data) {
											// alert("inData:"
											// + JSON.stringify(data));
											return {
												total : data.totalElements,
												rows : data.content
											};
										},
										onBeforeLoad : function(param) {
											param.page -= 1;
											param.size = param.rows;
											delete param.rows;

											param.sort = 'createTime,desc';

											var interfaceName = $('#txtIfName')
													.val();
											if (interfaceName != "") {
												param.interfaceName = interfaceName;
											}
											var systemId = $('#comboxSystem')
													.combobox('getValue');
											if (systemId != "") {
												param.systemId = systemId;
											}
											var fieldId = $('#comboxField')
													.combobox('getValue');
											if (fieldId != "") {
												param.fieldId = fieldId;
											}
										}
									});

					$("#datagrid").datagrid('getPager').pagination({
						displayMsg : '当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
					});
					$(".panel-tool-close, #instance_cancel").click(function(e) {
						$("body").css("overflow-x", "inherit")
					});

					$("#ensureSelect")
							.click(
									function(e) {
										var checkedNodes = $("#tt").tree(
												"getChecked");
										var selectSystems = "";
										for (var i = 0, len = checkedNodes.length; i < len; ++i) {
											var tempNode = checkedNodes[i];
											if (tempNode.nodeType != "fieldSystem") {
												continue;
											}
											selectSystems += (selectSystems != "" ? ","
													: "")
													+ tempNode.id;
										}
										$('#system_selection').window('close');
										var interfaceId = $(
												'#txtSelectInterfaceId').val();
										var jsonData = {
											interfaceId : interfaceId,
											systems : selectSystems
										};
										$
												.ajax({
													type : "get",
													url : BASE_URL_API
															+ '/channelSystemManagement/updateVisibleList?v='
															+ Math.random(),
													dataType : 'json',
													data : jsonData,
													contentType : "application/json",
													success : function(data) {
														if (data.result == '1') {
															$.messager
																	.alert(
																			'提示',
																			'<p>更新可见范围成功!</p>',
																			'info');
															$('#datagrid')
																	.datagrid(
																			'reload');
														} else {
															$.messager
																	.alert(
																			'错误',
																			'<p>'
																					+ data.msg
																					+ '</p>',
																			'error');
														}
														$("#txtAccessToken")
																.val(
																		data.access_token);
													},
													error : function() {
														$.messager
																.alert(
																		'错误',
																		'<p>服务异常，更新可访问列表失败，请稍后重试或联系管理员!</p>',
																		'error');
													}
												});
									});

					$("#searchNode").click(function(e) {
						if ($("#systemName").val() != '') {
							choose_tree();
						} else {
							$(".systemName").val("");
							var row = $('#tt li .tree-node');
							row.removeClass('tree-node-selected');
							$(".tree_con").scrollTop(0);
						}
					});

					$("#systemName").bind('input propertychange', function() {
						arrayLi = [];
						arrayLiInd = 0;
						if ($("#systemName").val() != '') {
							choose_tree();
						} else {
							$("#ff input").val("");
							var row = $('#tt li .tree-node');
							row.removeClass('tree-node-selected');
							$(".tree_con").scrollTop(0);
						}
					});

					$(document, "#systemName").keyup(function(event) {
						if (event.keyCode == 8) {
							$("#searchNode").trigger("click");
						}
					});
					$(document, "#systemName").keyup(function(event) {
						if (event.keyCode == 13) {
							$("#searchNode").trigger("click");
						}
					});

				});

// 查询
function search() {
	$('#datagrid').datagrid('reload');
}
function refresh() {
	$('#datagrid').datagrid('reload');
}

// 停用
function setDisable(index) {
	updateStatus(index, '0');
}
// 启用
function setEnable(index) {
	updateStatus(index, '1');
}
function updateStatus(index, status) {
	var msg = "停用";
	if (status == '1') {
		msg = "启用";
	}
	var row = $('#datagrid').datagrid('getData').rows[index];
	// alert("inData:"+JSON.stringify(row));
	var id = row.tokenId;
	var data = {
		id : id,
		status : status
	};
	$("#progressbar, #progressbar_tips").fadeIn();
	loading_point.timer = setInterval(loading, 200);
	$.ajax({
		type : "get",
		url : BASE_URL_API + '/channelSystemManagement/updateStatus?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			if (data.result == true) {
				$.messager.alert('提示', "<p>" + msg + "成功!</p>", 'info',
						function() {
							refresh();
						});
			} else {
				$.messager.alert('错误',
						'<p>服务异常，' + msg + '失败，请稍后重试或联系管理员!</p>', 'error');
			}

		},
		error : function() {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			$.messager.alert('错误', '<p>服务异常，' + msg + '失败，请稍后重试或联系管理员!</p>',
					'error');
		}
	});
}

function showDetial(rowIndex) {
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	var interfaceId = row.interfaceId;
	var interfaceName = row.interfaceName;
	var title = "服务浏览";
	var url = "/pages/esb/ServiceManagement/businessServiceView.html?interfaceId="
			+ window.encodeURI(interfaceId)+ '&interfaceName=' + window.encodeURI(interfaceName) + '&v=' + Math.random();
	var icon = $(this).attr("icon");
	window.parent.OpenTab(title, url, icon, true);
}

var loading_point = {
	timer : null,
	len : 3,
	count : 0
};
function loading() {
	if (loading_point.count < loading_point.len) {
		loading_point.count++;
		$("#progressbar_point").text($("#progressbar_point").text() + ".");
	} else {
		loading_point.count = 0;
		$("#progressbar_point").text("");
	}
}

function selVisibleList(rowIndex) {
	// if(treeData==null){
	$("#tt")
			.tree(
					{
						url : BASE_URL_TREE + '/getFieldSystemsForEasyUiTree'
								+ '?v=' + Math.random(),
						method : "get",
						lines : false,
						async : false,
						checkbox : true,
						loadFilter : function(data, parent) {
							treeData = [ {
								text : "全部",
								children : data,
								nodeType : "root"
							} ];
							return treeData;
						},
						onLoadSuccess : function() {
							$(
									"#tt > li > ul > li > ul > li > .tree-node > .tree-file")
									.css("background",
											"url('../../../images/st_folder.png') no-repeat 2px 2px");
							$("#tt > li > ul > li > .tree-node > .tree-file")
									.parent().parent().css("display", "none");
							reSetTree(rowIndex);
						},
						onClick : function(node) {
							if (node.checked) {
								$("#tt").tree("uncheck", node.target);
							} else {
								$("#tt").tree("check", node.target);
							}

							// $("#systemName").val(node.text);
							// choose_tree();
						}
					});
	// }else{
	// reSetTree()
	// }

	return false;
}

/* 树 */
// 点击分配打开用户授权修改页面
function onOpenEdit(rowIndex) {
	var rowData = $('#datagrid').datagrid('getRows')[parseInt(rowIndex, 10)];
	$.ajax({
		type : "get",
		url : BASE_URL_HTTP_INTERFACE + "/getFieldSystemRoot?id=" + rowData.id,
		dataType : "json",/*
							 * async:false,
							 */
		contentType : "application/json",
		success : function(data) {
			// fieldSystems = data;
			reBackData(rowData, data);
		},
		error : function() {
			$.messager.alert('错误', '<p>服务异常，修改用户授权信息失败，请稍后重试!</p>', 'error');
		}
	});

}

// 点击分配后要回显用户相关数据
function reBackData(rowData, data) {

	var systemsInfo = getSystemsStrFromSyslist(data);
	g_currSystemsStr = systemsInfo.names;
	$("#strFieldSystems").val(systemsInfo.ids);
	// $("#system").val(systemsInfo.names);
}

function onCancleEdit() {
	$('#winEdit').window('close');
}

function onSearch() {
	$('#datagrid').datagrid('load');
}

// 通过领域系统对象数组转成系统字符串
function getSystemsStrFromSyslist(fieldSystemsArr) {
	var systemsStr = "";
	var systemIdsStr = "";
	for (var i = 0, len = fieldSystemsArr.length; i < len; ++i) {
		if (!fieldSystemsArr[i]) {
			continue;
		}
		var fieldName = fieldSystemsArr[i].fieldName;
		var systemName = fieldSystemsArr[i].fieldSystemName;
		systemIdsStr += (systemIdsStr == "" ? "" : ",")
				+ fieldSystemsArr[i].fieldSystemId;
		systemsStr += systemName + (i == len - 1 ? "" : ",");
	}
	return {
		ids : systemIdsStr,
		names : systemsStr
	};
}

// 通过字符串获取系统列表
function getSystemListFromStr(fieldSystemsStr) {
	if (!fieldSystemsStr) {
		return [];
	}
	var fieldSystemList = fieldSystemsStr.split(",");
	var systemList = [];
	for (var i = 0, len = fieldSystemList.length; i < len; ++i) {
		if (!fieldSystemList[i]) {
			continue;
		}
		var systemName = fieldSystemList[i].split("-")[1];
		if (systemName) {
			systemList.push(systemName);
		}
	}
	return systemList;
}

// 通过字符串获取构造领域系统的树节点信息
function getFieldSystemNodesFromStr(fieldSystemsStr) {
	if (!fieldSystemsStr) {
		return [];
	}
	var fieldSystemList = fieldSystemsStr.split(",");
	var fieldList = [];
	var systemNodeList = [];
	for (var i = 0, len = fieldSystemList.length; i < len; ++i) {
		if (!fieldSystemList[i]) {
			continue;
		}
		var fieldName = fieldSystemList[i].split("-")[0];
		var systemName = fieldSystemList[i].split("-")[1];
		if (fieldName) {
			var tempNode = {};
			var j = 0;
			for (; j < fieldList.length; ++j) {
				if (fieldList[j].text == fieldName) {
					if (systemName) {
						fieldList[j].children.push({
							text : systemName,
							children : [],
							nodeType : "fieldSystem"
						});
					}
					break;
				}
			}
			if (j == fieldList.length) {
				tempNode.text = fieldName;
				tempNode.nodeType = "field";
				tempNode.children = [];
				if (systemName) {
					tempNode.children.push({
						text : systemName,
						children : [],
						nodeType : "fieldSystem"
					});
				}
				fieldList.push(tempNode);
			}
		}

	}
	return fieldList;
}

// 通过领域系统对象数组转换成树节点信息
function getFieldSystemNodesFromArr(fieldSystemsArr) {
	if (!fieldSystemsArr) {
		return [];
	}
	var fieldNodes = [];
	for (var i = 0, len = fieldSystemsArr.length; i < len; ++i) {
		if (!fieldSystemsArr[i]) {
			continue;
		}
		var fieldName = fieldSystemsArr[i].fieldName;
		var systemName = fieldSystemsArr[i].fieldSystemName;
		if (fieldName) {
			var tempNode = {};
			var j = 0;
			for (; j < fieldNodes.length; ++j) {
				if (fieldNodes[j].text == fieldName) {
					if (systemName) {
						fieldNodes[j].children.push({
							text : systemName,
							children : [],
							nodeType : "fieldSystem"
						});
					}
					break;
				}
			}
			if (j == fieldNodes.length) {
				tempNode.text = fieldName;
				tempNode.nodeType = "field";
				tempNode.children = [];
				if (systemName) {
					tempNode.children.push({
						text : systemName,
						children : [],
						nodeType : "fieldSystem"
					});
				}
				fieldNodes.push(tempNode);
			}
		}
	}
	return fieldNodes;
}

// 显示所属系统
function onShowDetail(rowIndex) {
	var rowData = $('#datagrid').datagrid('getRows')[parseInt(rowIndex, 10)];
	$.ajax({
		type : "get",
		url : BASE_URL_USER_SEARCH + "/getFieldSystemRoot?id=" + rowData.id,
		dataType : "json",
		contentType : "application/json",
		success : function(data) {
			// fieldSystems = data;

			var fieldSystemsNodes = getFieldSystemNodesFromArr(data);
			$("#sys_show_tt").tree("loadData", fieldSystemsNodes);
			$("#sys_show_tt > li > ul > li > .tree-node > .tree-file").css(
					"background",
					"url('../../images/st_folder.png') no-repeat 2px 2px");
			$("#system_show").window('setTitle', rowData.userCode + '所属系统');
			$('#system_show').window('open');
		},
		error : function() {
			$("#instance_save").linkbutton("enable");
			$("#instance_save .l-btn-text").text("保存");
			$.messager.alert('错误', '<p>服务异常，修改用户授权信息失败，请稍后重试!</p>', 'error');
		}
	});
}

function setChecked(sysName) {
	if(sysName!=null){
		sysName=sysName.replace(/(^\s*)|(\s*$)/g, "");
	}
	if (!sysName) {
		return;
	}
	$("#tt li .tree-node").each(function() {
		if ($(".tree-title", $(this)).text() == sysName) {
			$('#tt').tree('check', this);
			return false;
		}
	});

}

function setCheckedList(sysNameArr) {
	if (sysNameArr && sysNameArr.length) {
		for (var i = 0, len = sysNameArr.length; i < len; ++i) {
			setChecked(sysNameArr[i]);
		}
	}
}

function reSetTree(rowIndex) {
	$('#system_selection').window('open');
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	$('#txtSelectInterfaceId').val(row.interfaceId);
	var currSystemsStr = row.visibleListName;
	if (currSystemsStr !== '') {
		$("#systemName").val(currSystemsStr.split(",")[0]);
		choose_tree();
	} else {
		$("#systemName").val('');
		$(".tree_con").scrollTop(0);
		var row = $('#tt li .tree-node');
		row.removeClass('tree-node-selected');
	}

	var checkedNodes = $("#tt").tree("getChecked");
	if (checkedNodes) {
		$.each(checkedNodes, function(index, node) {
			$("#tt").tree("uncheck", node.target);
		});
	}
	// var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	// var currSystemsStr = row.visibleListName;
	if (currSystemsStr != '') {
		setCheckedList(currSystemsStr.split(","));
	}
}

function choose_tree() {
	$('#tt').tree('expandAll');
	if (arrayLi.length == 0 && arrayLiInd == 0) {
		var searchVal = $("#systemName").val().toUpperCase();
		var row = $('#tt li .tree-node');
		var rowcolumn = $('#tt li .tree-node > .tree-title');
		var i = 0, j = 0;
		var offsetC = 0
		row.removeClass('tree-node-selected');
		rowcolumn.each(function(column) {
			var matchVal = $(this).text();
			if (matchVal.indexOf(searchVal) != -1) {
				i++;
				var panel_top = parseInt($(this).parents(".panel").css("top"),
						10);

				if (i <= 1) {
					$(this).parent().addClass('tree-node-selected');
					var top = $(".tree_con").scrollTop() + $(this).offset().top
							- 76 - panel_top;
					$(".tree_con").scrollTop(top);
					arrayLiInd = 1;
				}
				arrayLi.push([
						matchVal,
						$(".tree_con").scrollTop() + $(this).offset().top - 76
								- panel_top ]);

			}
		});
	} else {
		var rowcolumn = $('#tt li .tree-node > .tree-title');
		var row = $('#tt li .tree-node');
		row.removeClass('tree-node-selected');

		if (arrayLiInd < arrayLi.length) {
			rowcolumn.each(function(column) {
				var matchVal = $(this).text();
				if (matchVal == arrayLi[arrayLiInd][0]) {
					$(this).parent().addClass('tree-node-selected');
					$(".tree_con").scrollTop(arrayLi[arrayLiInd][1]);
					arrayLiInd++;
					return false;
				}
			});
		} else {
			// arrayLi = [];
			arrayLiInd = 0;
			$(".tree_con").scrollTop(0);
			choose_tree();
		}
	}
}

/* 树 */
